package com.controller;

import com.alibaba.fastjson.JSON;
import com.dao.DeptDao;
import com.dao.UserDao;
import com.entity.DeptEntity;
import com.entity.MyReturn;
import com.entity.Userinfo;
import com.util.MySqlsessionFactory;
import com.util.MyTools;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet(name = "DeptServlet",urlPatterns = "/deptinfo")
public class DeptServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取并连接mysql数据库
        SqlSession sqlSession= MySqlsessionFactory.getSQLSession();
        DeptDao deptDao = sqlSession.getMapper(DeptDao.class);
        // 获取前端传来的method的值，根据其值来判断进行什么操作
        String method = req.getParameter("method");
        // 创建用户实体类 DeptEntity
        DeptEntity deptEntity = new DeptEntity();

        MyReturn myReturn = new MyReturn();
        // 设置一个默认为零的参数，后续用来保存 sql语句的影响条数
        int num = 0;
        // 通过switch 判断下一步进行的操作
        switch (method) {
            case "selectDept":

                // 通过list<DeptEntity>获取查到的所有部门信息，每个用户是一个实体类，类似于之前的map
                List<DeptEntity> deptEntityList = deptDao.selectDept();
                myReturn.setCode(0);
                myReturn.setMsg("");
                myReturn.setData(deptEntityList);
                break;

        }
        // 将返回对象转为json对象
        String jsonStr = JSON.toJSONString(myReturn);
        resp.getWriter().write(jsonStr);
        // 提交事务
        sqlSession.commit();
        // 关闭mysql连接
        sqlSession.close();
    }
}
